class UsersController < ApplicationController
  before_filter :login_required, :authorization_required
  
  def index
    if params[:query].nil?
      @users = User.find(:all, :conditions => "enabled = true", :order => 'login asc')
    else
      @users = User.find(:all, :conditions => ["enabled = true and login like ? or email like ?", "%#{params[:query]}%", "#{params[:query]}%"], :order => 'login asc')
    end
    respond_to do |format|
      format.html {render :action => 'list.rhtml'}
      format.js {render :action => 'list.rjs'}
      format.xml {render :xml => @users.to_xml}
    end
  end
  
  def new
    @user = User.new
    @roles = Role.find(:all)
    respond_to do |format|
      format.html {render :action => 'new.rhtml'}
      format.js {render :action => 'new.rjs'}
    end
  end
  
  def create
    @user = User.new(params[:user]) 
    if @user.save
      index
    else
      render :action => 'new' unless request.xhr?
    end
  end
  
  def edit
    @user = User.find(params[:id])
    @roles = Role.find(:all)
    respond_to do |format|
      format.html {render :action => 'edit.rhtml'}
      format.js {render :action => 'edit.rjs'}
    end
  end
  
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      index
    else
      render :action => 'edit' unless request.xhr?
    end
  end
  
  def destroy_selected
    unless params[:selected].nil?
      params[:selected].each do |id|
        user = User.find(id)
        user.enabled = false
        user.save
      end
    end
    respond_to do |format|
      format.html {redirect_to :action => 'list'}
      format.js do
        @users = User.find(:all, :conditions => "enabled = true", :order => 'login asc')
        render :action => 'list.rjs'
      end
    end
  end
  
  def destroy
    user = User.find(params[:id])
    user.enabled = false
    user.save
    redirect_to :action => 'list' unless request.xhr?
  end
 
end
